package com.phkj.qdh.ui.fragment.drafts


import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.OnBackPressedCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter4.QuickAdapterHelper
import com.google.gson.reflect.TypeToken
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.hjq.toast.ToastUtils
import com.lxj.xpopup.XPopup
import com.lxj.xpopupext.listener.TimePickerListener
import com.lxj.xpopupext.popup.TimePickerPopup
import com.phkj.qdh.R
import com.phkj.qdh.bean.Child
import com.phkj.qdh.bean.DeptUserVo
import com.phkj.qdh.bean.DraftBean
import com.phkj.qdh.bean.FileUploadBean
import com.phkj.qdh.bean.LawDraftBean
import com.phkj.qdh.bean.LawOrTeamInspectBean
import com.phkj.qdh.bean.TeamScoreBean
import com.phkj.qdh.databinding.FragmentDraftLawBinding
import com.phkj.qdh.net.FILE_UPLOAD
import com.phkj.qdh.net.msg
import com.phkj.qdh.ui.adapter.AddFileHeadAdapter
import com.phkj.qdh.ui.adapter.CommonSelectBean
import com.phkj.qdh.ui.adapter.FileTitleAdapter
import com.phkj.qdh.ui.adapter.ImagerViewAdapter
import com.phkj.qdh.ui.adapter.ImagerViewAddAdapter
import com.phkj.qdh.ui.adapter.UploadFileBean
import com.phkj.qdh.ui.dialog.CommonConfirmDialog
import com.phkj.qdh.ui.dialog.CommonConfirmListener
import com.phkj.qdh.ui.dialog.CommonSelectDialog
import com.phkj.qdh.ui.dialog.CommonSelectSingleListener
import com.phkj.qdh.ui.dialog.EmployeeSelectDialog
import com.phkj.qdh.ui.dialog.EmployeeSelectListener
import com.phkj.qdh.ui.dialog.MyTimeSelectDialog
import com.phkj.qdh.ui.dialog.SelectSortListener
import com.phkj.qdh.ui.dialog.TeamOrLawTreeSelectDialog
import com.phkj.qdh.ui.fragment.teaminspect.TeamInspectVM
import com.phkj.qdh.ui.fragment.teaminspect.getTeamInspectVMProvider
import com.phkj.qdh.utils.FileHelper
import com.phkj.qdh.utils.GetImgContract
import com.phkj.qdh.utils.LogUtil
import com.phkj.qdh.utils.MyItemDecoration
import com.phkj.qdh.utils.SPSUtils
import com.phkj.qdh.utils.SPS_DRAFTS
import com.phkj.qdh.utils.TakePhoto
import com.phkj.qdh.utils.gone
import com.phkj.qdh.utils.launchAndRepeatWithViewLifecycle
import com.phkj.qdh.utils.requestMain
import com.phkj.qdh.utils.visible
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collectLatest
import rxhttp.wrapper.utils.GsonUtil
import rxhttp3.RxHttp
import rxhttp3.toFlowResponse
import java.io.File
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.GregorianCalendar
import java.util.Locale

private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * 执法巡查提交
 */
class DraftLawFragment : Fragment() {
    private var param1: LawOrTeamInspectBean? = null
    private var data: LawDraftBean? = null
    private var param2: Int? = null
    private lateinit var vm: TeamInspectVM
    private var _binding: FragmentDraftLawBinding? = null
    private val binding get() = _binding!!
    private val iVAdapter by lazy { ImagerViewAdapter() }
    private val iVAddAdapter by lazy { ImagerViewAddAdapter() }
    private val addFileHeadAdapter by lazy { AddFileHeadAdapter() }
    private val fileTitleAdapter by lazy { FileTitleAdapter() }
    private var imageUri: Uri? = null
    private var filePath: String = ""
    private var secondType: Int? = null
    private var secondPos: Int? = null
    private var rectificationStatus: Int? = null
    private var disposalId: Int? = null
    private var disposalBean: TeamScoreBean? = null
    private var thirdType: Int? = null
    private var policyIds = ArrayList<Int>()
    private val takePic =
        registerForActivityResult(ActivityResultContracts.TakePicture()) { boolean ->
            if (boolean) {
                try {
                    imageUri?.let { uri ->
                        val option = BitmapFactory.Options()
                        option.inPreferredConfig = Bitmap.Config.RGB_565
                        val bitmap = BitmapFactory.decodeStream(
                            requireContext().contentResolver.openInputStream(uri), null, option
                        )
                        val yasuohou = TakePhoto.scaleBitmap(bitmap, 0.5f)
                        val path = TakePhoto.saveBitmap2File(yasuohou)
                        uploadImg(path)
                    }

                } catch (e: Exception) {

                }

            }
        }

    private val getFile = registerForActivityResult(ActivityResultContracts.GetContent()) {
        it?.let { it1 ->
            val filePath = FileHelper.getFileAbsolutePath(requireContext(), it)
            uploadFile(filePath)
        }
    }

    private val selectImg = registerForActivityResult(GetImgContract()) { uri ->
        uri?.let {
            LogUtil.E(it.toString())
            val file = FileHelper.getFileAbsolutePath(requireContext(), it)
            uploadImg(file)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            data = it.getParcelable(ARG_PARAM1)
            param2 = it.getInt(ARG_PARAM2)
        }
        requireActivity().onBackPressedDispatcher.addCallback(this,
            object : OnBackPressedCallback(true) {
                override fun handleOnBackPressed() {
                    parentFragmentManager.popBackStack()
                }
            })
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentDraftLawBinding.inflate(inflater, container, false)
        vm = ViewModelProvider(this, getTeamInspectVMProvider())[TeamInspectVM::class.java]
        return binding.root
    }


    @RequiresApi(Build.VERSION_CODES.N)
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        param1 = data!!.headBean
        if (param1 == null) {
            parentFragmentManager.popBackStack()
        }
        data?.let {
            binding.tvSort2.text = data?.secondType
            secondType = data?.secondTypeId
            secondPos = data?.secondPos
            thirdType = data?.thirdId
            if (data?.third.isNullOrBlank()) {
                binding.llQuest1.gone()
            }

            it.banfa?.let { banfa ->
                binding.tvBanFa.text = banfa.name
                binding.tvFen.text = banfa.score.toString()
                disposalId = banfa.id
                disposalBean = banfa
            }
            policyIds.clear()
            it.zerenIds?.let { it1 -> policyIds.addAll(it1) }
            binding.tvZeren.text = it.zeren ?: ""
            binding.edt.setText(it.questDetail ?: "")
            binding.edtRemark.setText(it.remark ?: "")
            rectificationStatus = it.rectificationStatus
            if (rectificationStatus == 0) {
                binding.llDate.visible()
                binding.tvDate.text = it.date
                binding.tvRectifyState.text = "为整改"
            } else {
                binding.llDate.gone()
                binding.tvRectifyState.text = "已整改"
            }
            iVAdapter.submitList(it.imgList)
            fileTitleAdapter.submitList(it.fileList)
        }
        binding.run {
            tvSort1.text = param1?.name ?: ""
            llQuest.setOnClickListener {

                param1?.child?.let { list ->
                    val dialog = TeamOrLawTreeSelectDialog(requireContext(), list as ArrayList)
                    dialog.setTitle("${param1?.name}问题")
                    dialog.setSelectSortListener(object : SelectSortListener {
                        @SuppressLint("SetTextI18n")
                        override fun ok(data: Pair<Child?, Child?>) {
                            secondType = data.first?.id
                            thirdType = data.second?.id
                            if (data.second != null) {
                                tvSort2.text = "${data.first?.name}-${data.second?.name ?: ""}"

                            } else {
                                tvSort2.text = data.first?.name
                            }
                        }
                    })
                    XPopup.Builder(requireContext()).asCustom(dialog).show()
                }/*



                    val selectList =
                        param1?.child?.map { a -> CommonSelectBean(a.name, false) } as ArrayList
                    val dialog = CommonSelectDialog(requireContext(), selectList, true)
                    dialog.setTitle("${param1?.name}问题")
                    dialog.setUnSelectTips("请选择一个${param1?.name}问题")
                    dialog.setSingleResultListener(object : CommonSelectSingleListener {
                        override fun ok(pos: Int) {
                            val data = param1!!.child[pos]
                            tvSort2.text = data.name
                            secondType = data.id
                            secondPos = pos
                            if (data.child.isNullOrEmpty()) {
                                llQuest1.gone()
                                thirdType = null
                            } else {
                                llQuest1.visible()
                            }
                        }
                    })
                    XPopup.Builder(requireContext()).dismissOnTouchOutside(true).asCustom(dialog).show()*/

            }
            llQuest1.setOnClickListener {
                secondPos?.let { pos1 ->
                    val selectList = param1?.child?.get(pos1)?.child?.map { a ->
                        CommonSelectBean(
                            a.name, false
                        )
                    } as ArrayList

                    selectList?.let { thrd ->
                        val dialog = CommonSelectDialog(requireContext(), thrd, true)
                        dialog.setTitle("${param1?.name}问题")
                        dialog.setUnSelectTips("请选择一个${param1?.name}问题")
                        dialog.setSingleResultListener(object : CommonSelectSingleListener {
                            override fun ok(pos: Int) {
                                val data = param1!!.child[secondPos!!].child?.get(pos)
                                tvSort21.text = data?.name
                                thirdType = data?.id
                            }
                        })
                        XPopup.Builder(requireContext()).dismissOnTouchOutside(true)
                            .asCustom(dialog).show()
                    }


                }


            }

            ivBack.setOnClickListener {
                parentFragmentManager.popBackStack()
            }
            rvLawSubmit.run {
                layoutManager =
                    LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
                addItemDecoration(
                    MyItemDecoration(
                        ContextCompat.getColor(requireContext(), R.color.transparent),
                        28,
                        RecyclerView.HORIZONTAL
                    )
                )
            }
            rvLawFile.run {
                layoutManager =
                    LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
                addItemDecoration(
                    MyItemDecoration(
                        ContextCompat.getColor(
                            requireContext(), R.color.transparent
                        ), 25, RecyclerView.HORIZONTAL
                    )
                )
            }
            llBanfa.setOnClickListener {
                vm.getScoreList(2)
            }
            btnCaogao.setOnClickListener {
                val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                val lawDraftBean = LawDraftBean(
                    param1!!,
                    tvSort2.text.toString(),
                    secondType,
                    secondPos,
                    tvSort21.text.toString(),
                    thirdType,
                    binding.edt.text.toString(),
                    iVAdapter.items,
                    fileTitleAdapter.items,
                    binding.tvZeren.text.toString(),
                    policyIds,
                    rectificationStatus,
                    binding.tvDate.text.toString(),
                    disposalBean,
                    binding.edtRemark.text.toString(),
                    dateFormat.format(System.currentTimeMillis())
                )
                try {
                    val localDraft = GsonUtil.fromJson<ArrayList<DraftBean>>(
                        SPSUtils.getString(
                            SPS_DRAFTS, ""
                        ), object : TypeToken<ArrayList<DraftBean>>() {}.type
                    )
                    localDraft.add(0, DraftBean(localDraft.size + 1, 3, null, null, lawDraftBean))
                    SPSUtils.put(SPS_DRAFTS, GsonUtil.toJson(localDraft))
                } catch (e: Exception) {
                    e.printStackTrace()
                    SPSUtils.put(
                        SPS_DRAFTS,
                        GsonUtil.toJson(arrayListOf(DraftBean(0, 3, null, null, lawDraftBean)))
                    )
                }
                ToastUtils.show("已保存为草稿")
                parentFragmentManager.popBackStack(
                    "draft", FragmentManager.POP_BACK_STACK_INCLUSIVE
                )

            }
            llDate.setOnClickListener {
                val format = SimpleDateFormat("yyyy-MM-dd HH:mm:00")
                val dialog = MyTimeSelectDialog.newInstance(context = requireContext())
                val date = Date()
                val calender = Calendar.getInstance()
                calender.time = date
                dialog.setDateRange(calender, null)
                dialog.setMode(TimePickerPopup.Mode.YMDHM)
                dialog.setTitle("请选择整改日期")
                dialog.setTimePickerListener(object : TimePickerListener {
                    override fun onTimeChanged(date: Date) {
                    }

                    override fun onTimeConfirm(date: Date, view: View) {
//                        val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:00")
//                        val parse = simpleDateFormat.parse(binding.tvDate.text.toString())
                        if (System.currentTimeMillis() >= date.time) {
                            ToastUtils.show("整改时间必须大于当前时间")
                            return
                        }

                        tvDate.text = format.format(date.time)
                    }

                    override fun onCancel() {
                    }
                })
                XPopup.Builder(requireContext()).enableDrag(false).asCustom(dialog).show()
            }
            llZeren.setOnClickListener {
                vm.getEmployee()
            }
            llIsRectify.setOnClickListener {
                val dialog =
                    CommonConfirmDialog.getInstance("整改情况", "是否已整改", "已整改", "未整改")
                dialog.setCancelListener(object : CommonConfirmListener {
                    override fun dOk() {
                        llDate.gone()
                        tvDate.text = ""
                        tvRectifyState.text = "已整改"
                        rectificationStatus = 1
                    }

                    override fun dCancel() {
                        llDate.visible()
                        rectificationStatus = 0
                        tvRectifyState.text = "未整改"
                    }
                })
                dialog.show(parentFragmentManager, "")
            }
            btnOk.setOnClickListener {
                if (binding.tvSort2.text.toString().isBlank()) {
                    ToastUtils.show("请选择执法问题")
                    return@setOnClickListener
                }
                if (binding.tvRectifyState.text.toString().isBlank()) {
                    ToastUtils.show("请选择整改情况")
                    return@setOnClickListener
                }
                if (binding.tvZeren.text.toString().isBlank()) {
                    ToastUtils.show("请选择责任人")
                    return@setOnClickListener
                }
                if (disposalId == null) {
                    ToastUtils.show("请选择处置办法")
                    return@setOnClickListener
                }
                if (rectificationStatus == 0) {
                    if (binding.tvDate.text.toString().isBlank()) {
                        ToastUtils.show("请选择整改日期")
                        return@setOnClickListener
                    } else {
                        val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:00")
                        val parse = simpleDateFormat.parse(binding.tvDate.text.toString())
                        if (System.currentTimeMillis() >= parse.time) {
                            ToastUtils.show("整改时间必须大于当前时间")
                            return@setOnClickListener
                        }
                    }
                }
                if (iVAdapter.items.isEmpty()) {
                    ToastUtils.show("请上传照片")
                    return@setOnClickListener
                }

                val dialog = CommonConfirmDialog.getInstance("提交", "确定要提交吗")
                dialog.setCancelListener(object : CommonConfirmListener {
                    override fun dOk() {

                        val map = HashMap<String, Any?>()
                        map["images"] = iVAdapter.items
                        map["files"] = fileTitleAdapter.items
                        map["policyIds"] = policyIds
                        map["inspectId"] = 2
                        map["firstType"] = param1?.id
                        map["eventType"] = 0
                        map["thirdType"] = thirdType
                        map["secondType"] = secondType
                        map["disposalId"] = disposalId //处置办法
                        map["problemDetail"] = binding.edt.text.toString()
                        map["remark"] = binding.edtRemark.text.toString()
                        map["rectificationStatus"] = rectificationStatus ?: 0
                        if (rectificationStatus != null && rectificationStatus == 0) {
                            map["rectificationPeriod"] = binding.tvDate.text.toString()
                        }

                        vm.saveLawInspect(map)
                    }

                    override fun dCancel() {}
                })
                dialog.show(parentFragmentManager, "")

            }
        }


        val fileHelper = QuickAdapterHelper.Builder(fileTitleAdapter).build()
        fileHelper.addBeforeAdapter(addFileHeadAdapter)
        addFileHeadAdapter.add("")
        binding.rvLawFile.adapter = fileHelper.adapter
        addFileHeadAdapter.setOnItemClickListener { _, _, _ ->
            if (fileTitleAdapter.items.size >= 6) {
                return@setOnItemClickListener
            }
            getFile.launch("application/msword")
        }

        val helper = QuickAdapterHelper.Builder(iVAdapter).build()
        helper.addBeforeAdapter(iVAddAdapter)
        iVAddAdapter.add("s")
        binding.rvLawSubmit.adapter = helper.adapter

        iVAdapter.addOnItemChildClickListener(R.id.iv_delete) { adapter, _, pos ->
            val dialog = CommonConfirmDialog.getInstance(
                "删除图片", "确定要删除图片吗", "确定", "取消"
            )
            dialog.setCancelListener(object : CommonConfirmListener {
                override fun dOk() {
                    adapter.removeAt(pos)
                }

                override fun dCancel() {
                    takePhoto()
                }

            })
            dialog.show(parentFragmentManager, "")
        }

        iVAddAdapter.setOnItemClickListener { adapter, data, pos ->
            if (iVAdapter.items.size >= 6) {
                ToastUtils.show("图片数量不能超过6张")
                return@setOnItemClickListener
            }
            XXPermissions.with(requireContext()).permission(
                arrayListOf(
                    Permission.READ_MEDIA_IMAGES, Permission.CAMERA, Permission.READ_MEDIA_IMAGES
                )
            ).request(object : OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    if (allGranted) {
                        val dialog = CommonConfirmDialog.getInstance(
                            "上传图片", "请选择上传方式", "选择照片", "拍照"
                        )
                        dialog.setCancelListener(object : CommonConfirmListener {
                            override fun dOk() {
                                selectImg.launch(null)
                            }

                            override fun dCancel() {
                                takePhoto()
                            }

                        })
                        dialog.show(parentFragmentManager, "")
                    }
                }

                override fun onDenied(
                    permissions: MutableList<String>, doNotAskAgain: Boolean
                ) {
                    super.onDenied(permissions, doNotAskAgain)
                }
            })
        }


        launchAndRepeatWithViewLifecycle {
            vm.saveLawInspectResult.collectLatest {
                if (it) {
                    ToastUtils.show("提交成功")
                    try {
                        val json = SPSUtils.getString(SPS_DRAFTS, "")
                        LogUtil.E(json)
                        val data = GsonUtil.fromJson<ArrayList<DraftBean>>(
                            json, object : TypeToken<ArrayList<DraftBean>>() {}.type
                        )
                        param2?.let { id ->
                            data.removeIf { d -> d.id == id }
                        }
                        SPSUtils.put(SPS_DRAFTS, GsonUtil.toJson(data))
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                    parentFragmentManager.popBackStack(
                        "draft", FragmentManager.POP_BACK_STACK_INCLUSIVE
                    )
                }
            }
        }

        launchAndRepeatWithViewLifecycle {
            vm.scoreList.collectLatest {
                val showList = it.map { score -> CommonSelectBean(score.name) } as ArrayList
                val dialog = CommonSelectDialog(requireContext(), showList, true)
                dialog.setTitle("处置办法")
                dialog.setUnSelectTips("请选择一个处置办法")
                dialog.setSingleResultListener(object : CommonSelectSingleListener {
                    override fun ok(pos: Int) {
                        binding.tvBanFa.text = it[pos].name
                        binding.tvFen.text = it[pos].score.toString()
                        disposalId = it[pos].id
                        disposalBean = it[pos]
                    }
                })
                XPopup.Builder(requireContext()).dismissOnTouchOutside(true).asCustom(dialog).show()

            }
        }

        launchAndRepeatWithViewLifecycle {
            vm.employee.collectLatest {
                // 选择审批人
                val dialog = EmployeeSelectDialog(requireContext(), it)
                dialog.setListener(object : EmployeeSelectListener {
                    override fun ok(list: ArrayList<DeptUserVo>) {
                        val sb = StringBuilder()
                        policyIds.clear()
                        list.forEach { bean ->
                            sb.append(bean.userNamePhone)
                            sb.append("\n")
                            policyIds.add(bean.userId)
                        }
                        binding.tvZeren.text =
                            if (sb.length > 1) sb.deleteCharAt(sb.length - 1).toString() else ""
                    }
                })
                XPopup.Builder(requireContext()).asCustom(dialog).show()
            }
        }


    }


    private fun takePhoto() {
        val simpleDate = SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault())
        val fileName = simpleDate.format(GregorianCalendar().time) + ".jpg"
        var outputImage = File(requireContext().externalCacheDir, fileName)
        if (outputImage.exists()) {
            outputImage.delete()
        }
        outputImage.createNewFile()
        imageUri = if (Build.VERSION.SDK_INT >= 24) {
            FileProvider.getUriForFile(
                requireContext(), "com.phkj.qdh.fileprovider", outputImage
            )
        } else {
            Uri.fromFile(outputImage)
        }
        filePath = outputImage.absolutePath
        takePic.launch(imageUri)

    }

    private fun uploadImg(path: String) {
        requestMain {
            RxHttp.postForm(FILE_UPLOAD).addFile("file", path).toFlowResponse<FileUploadBean>()
                .catch { cause ->
                    ToastUtils.show(cause.msg)
                }.collectLatest {
                    delay(500)
                    iVAdapter.add(it.url)
                }
        }
    }


    private fun uploadFile(uri: String) {
        LogUtil.E("$uri")
        requestMain {
            RxHttp.postForm(FILE_UPLOAD).addFile("file", uri).toFlowResponse<FileUploadBean>()
                .catch { cause ->
                    ToastUtils.show(cause.msg)
                }.collectLatest {
                    delay(2000)
                    val name = uri.split("/")
                    fileTitleAdapter.add(UploadFileBean(name[name.size - 1], it.url))
                }
        }
    }

    companion object {
        /**
         *
         */
        @JvmStatic
        fun newInstance(param1: LawDraftBean, param2: Int) = DraftLawFragment().apply {
            arguments = Bundle().apply {
                putParcelable(ARG_PARAM1, param1)
                putInt(ARG_PARAM2, param2)
            }
        }
    }
}